<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :offset="6">
        <el-card :bordered="true" style="margin-top: 20%">
          <p slot="title">管理平台</p>
          <el-form ref="formInline" :model="formInline" :rules="ruleInline">
            <el-form-item prop="username" label="用户名">
              <el-input
                type="text"
                v-model="formInline.username"
                placeholder="Username"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码">
              <el-input
                type="password"
                v-model="formInline.password"
                placeholder="Password"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSubmit('formInline')">
                Login
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { Login } from '@/apis/auth'
import * as config from '@/config'
import router from '@/routers'

export default {
  name: 'Login',
  data() {
    return {
      formInline: {
        username: '',
        password: '',
      },
      ruleInline: {
        username: [
          {
            required: true,
            message: 'Please fill in the username name',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: 'Please fill in the password.',
            trigger: 'blur',
          },
          {
            type: 'string',
            min: 5,
            message: 'The password length cannot be less than 6 bits',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    handleSubmit(name) {
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          let res = null
          try {
            res = await Login(this.formInline)
          } catch (error) {
            this.$message.error('用户名密码错误!')
            return
          }

          const { token } = res
          localStorage.setItem(config.AUTH_TOKEN, JSON.stringify(token || ''))
          localStorage.setItem(config.USER_INFO, JSON.stringify(res))
          router.push('/')
        } else {
          this.$message.error('Fail!')
        }
      })
    },
  },
}
</script>

<style scoped>
.login-container {
  min-height: 100%;
  width: 100%;
  background-el-color: #2d3a4b;
  overflow: hidden;
}
</style>
